import { fetchDictionariesItem } from "@/service/common";
import { CustomerEconomicInfo, IDictionaries, IDictionariesItem } from "@/service/type";
import { useRequest } from "ahooks";
import { useForm } from "rc-field-form";
import { useEffect, useMemo, useState } from "react";
import { UserInfo } from "@/service/type";
import useAppAction from "@/hooks/useAppAction";
import useAppContext from "@/hooks/useAppContext";
import Taro, { useRouter } from "@tarojs/taro";
import { fetchUpdateUserInfo } from "./service";

type PageParams = {
  title: string;
  type: "signature" | "job" | "condition" | "character" | 'photo';
};

type NestedKeys<T> =
  T extends object ? { [K in keyof T]-?: K | NestedKeys<T[K]> }[keyof T] : never;

export type Keys = NestedKeys<UserInfo>

function useData() {
  const [form] = useForm<UserInfo>();
  const [drawerVisible, setDrawerVisible] = useState<boolean>(false)
  const [currentLabel, setCurrentLabel] = useState<Keys>('age')
  const [activeLabels, setActiveLabels] = useState<string[]>([])
  const userInfo = useAppContext((state) => state.userInfo);
  const refresh = useAppAction((action) => action.refresh);
  const { params } = useRouter<PageParams>();

  /**更新用户信息 */
  const { run: updateUserInfo } = useRequest(
    (options: Partial<UserInfo>) => fetchUpdateUserInfo(options),
    {
      manual: true,
      onSuccess() {
        Taro.showToast({ icon: "none", title: "修改成功" });
        refresh();
        setTimeout(() => {
          Taro.navigateBack()
        }, 1500)
      },
    }
  );

  /** 查询当前标签下的标签项 */
  const { data: list, run: queryListData } = useRequest(
    (type: IDictionaries) => fetchDictionariesItem(type),
    {
      manual: true,
      formatResult: (e) => e.res,
    }
  );

  useEffect(() => {
    Taro.setNavigationBarTitle({
      title: params.title,
    });
  }, []);

  /** 判断当前标签是否可以多选 */
  const isMultipe = useMemo(() => {
    return multipleList.indexOf(currentLabel) !== -1
  }, [currentLabel])

  /** 显示标签选择器 */
  const onShowDrawerPanel = (name: Keys, type: IDictionaries) => {
    setDrawerVisible(true)
    setCurrentLabel(name)
    queryListData(type)
    setActiveLabels(form.getFieldValue(name).split(',') || [])
  }

  /** 选择标签 */
  const onSelectedLabelItem = (data: IDictionariesItem[]) => {
    const values = data.map(item => item.value)
    const labels = data.map(item => item.label)
    form.setFieldsValue({
      [currentLabel]: values.join(','),
      [currentLabel + 'Cn']: labels.join(',')
    })
    setActiveLabels(form.getFieldValue(currentLabel).split(',') || [])
  }

  return {
    list: list || [],
    form,
    drawerVisible,
    userInfo,
    params,
    activeLabels,
    isMultipe,
    setDrawerVisible,
    onShowDrawerPanel,
    updateUserInfo,
    onSelectedLabelItem,
  }
}

export default useData
/** 可以多选的字段 */
export const multipleList: Keys[] = ['familyStructure', 'appearance', 'characterTags', 'hobbyTags']